<template>
  <div>
    <div class="flex items-center gap-2 mb-3">
      <select v-model="asset" class="border rounded p-2">
        <option v-for="a in assets" :key="a" :value="a">{{a}}</option>
      </select>
      <div class="flex gap-2">
        <button v-for="r in ranges" :key="r" @click="range = r"
          :class="['px-3 py-1 rounded-md border text-sm', r===range ? 'bg-blue-600 text-white' : 'bg-white text-gray-700']">{{r}}</button>
      </div>
    </div>
    <v-chart ref="chartRef" :option="option" autoresize style="height:360px; width:100%" />
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart } from 'echarts/charts'
import { GridComponent, TooltipComponent, LegendComponent } from 'echarts/components'
import VChart from 'vue-echarts'
import { getVolatilityData } from '../api/mockData.js'

import { useResize } from '../composables/useResize'

const chartRef = ref(null)
useResize(() => chartRef.value?.resize())

use([CanvasRenderer, LineChart, GridComponent, TooltipComponent, LegendComponent])

const assets = ['BTC','ETH','SOL']
const ranges = ['1D','1W','1M','3M']

const asset = ref('BTC')
const range = ref('1M')
const data = ref([])

function load(){ data.value = getVolatilityData(asset.value, range.value) }
watch([asset, range], load, { immediate: true })

const option = computed(()=> ({
  tooltip: { trigger: 'axis' },
  legend: { data: [asset.value] },
  xAxis: { type: 'category', data: data.value.map(p=>p.date) },
  yAxis: { type: 'value', name: '%' },
  grid: { left: '6%', right: '4%', bottom: '8%' },
  series: [{ name: asset.value, type: 'line', data: data.value.map(p=>p.value), smooth: true, areaStyle: {} }]
}))
</script>
